package com.xfcycle.zebrabikegp.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.UserInfoByUidResult;
import com.xfcycle.zebrabikegp.constant.MyProfileConstant;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.customView.BottomPopWindow;
import com.xfcycle.zebrabikegp.util.BitmapUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xfcycle.zebrabikegp.util.SystemActivityIntentUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class MyProfileActivity extends RootActivity {

    private static final String TAG = "MyProfileActivity";

    private ImageView iv_my_profile_back;

    private LinearLayout ll_my_profile_container;

    private RelativeLayout rl_my_profile_photo;
    private RelativeLayout rl_my_profile_name;
    private RelativeLayout rl_my_profile_mobile;
    private RelativeLayout rl_my_profile_email;
    private RelativeLayout rl_my_profile_password;
    private RelativeLayout rl_my_profile_gender;

    private ImageView iv_my_profile_user_portrait;

    private TextView tv_my_profile_name_content;
    private TextView tv_my_profile_mobile_content;
    private TextView tv_my_profile_email_content;
    private TextView tv_my_profile_gender_content;

    private Bundle bundle;
    private String uid;

    private BottomPopWindow bottomPopWindow;

    private String imageFilePath;

    private Bitmap userPortrait;

    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);

        bundle = this.getIntent().getExtras();

        initView();
        initViewListener();
        getDataFromWeb();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setViewContent();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        iv_my_profile_back = (ImageView) findViewById(R.id.iv_my_profile_back);

        ll_my_profile_container = (LinearLayout) findViewById(R.id.ll_my_profile_container);

        rl_my_profile_photo = (RelativeLayout) findViewById(R.id.rl_my_profile_photo);
        rl_my_profile_name = (RelativeLayout) findViewById(R.id.rl_my_profile_name);
        rl_my_profile_mobile = (RelativeLayout) findViewById(R.id.rl_my_profile_mobile);
        rl_my_profile_email = (RelativeLayout) findViewById(R.id.rl_my_profile_email);
        rl_my_profile_password = (RelativeLayout) findViewById(R.id.rl_my_profile_password);
        rl_my_profile_gender = (RelativeLayout) findViewById(R.id.rl_my_profile_gender);

        iv_my_profile_user_portrait = (ImageView) findViewById(R.id.iv_my_profile_user_portrait);

        tv_my_profile_name_content = (TextView) findViewById(R.id.tv_my_profile_name_content);
        tv_my_profile_email_content = (TextView) findViewById(R.id.tv_my_profile_email_content);
        tv_my_profile_mobile_content = (TextView) findViewById(R.id.tv_my_profile_mobile_content);
        tv_my_profile_gender_content = (TextView) findViewById(R.id.tv_my_profile_gender_content);

        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);

        bottomPopWindow = new BottomPopWindow(this, ll_my_profile_container, new String[]{"Take photo", "Choose from phone"}) {
            //跳转自定义相框获取照片
            @Override
            public void lineZeroListener() {
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                imageFilePath = getPortraitPath(MyProfileConstant.USER_PORTRAIT_FILE_NAME);

                if(null == imageFilePath){
                    Log.e(TAG, "lineZeroListener: 存储照片地址为null，无法进行下一步操作");
                    return;
                }

                //利用content传递uri地址，这里也可以采用FileProvider的方式（针对7.0及以上版本无法在不同app间传递uri的问题）
                File imagePath = new File(getExternalCacheDir(),"");
                File newFile = new File(imagePath,MyProfileConstant.USER_PORTRAIT_FILE_NAME);
                Uri contentUri = FileProvider.getUriForFile(MyProfileActivity.this,"com.xfcycle.zebrabikegp.fileprovider",newFile);

                Log.e(TAG, "lineZeroListener: ------------------"+contentUri+"------------"+imageFilePath);

                //设置照相机返回的照片存储路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                startActivityForResult(intent,REQUEST_CODE_GET_SYSTEM_CAMERA);
            }

            //跳转系统相册获取照片
            @Override
            public void lineOneListener() {
                Intent intent = SystemActivityIntentUtil.getPicturesIntent();
                startActivityForResult(intent,REQUEST_CODE_GET_SYSTEM_PICTURE);
            }

            @Override
            public void lineTwoListener() {
            }

            @Override
            public void lineThreeListener() {
            }

            @Override
            public void lineFourListener() {
            }

            @Override
            public void lineFiveListener() {
            }
        };
    }

    /**
     * 组件监听事件添加
     */
    private void initViewListener() {
        //回退事件监听
        iv_my_profile_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setResult(RESULT_OK);
                finish();
            }
        });

        //展示自定义用户头像控件
        rl_my_profile_photo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomPopWindow.showing();
            }
        });

        //修改用户名称
        rl_my_profile_name.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> params = new HashMap<>();
                params.put("uid",uid);
                params.put("username",tv_my_profile_name_content.getText().toString());
                activityChange(MY_PROFILE_NAME_ACTIVITY,params,REQUEST_CODE_MY_PROFILE_NAME_CHANGE);
            }
        });

        //修改手机号
        rl_my_profile_mobile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> params = new HashMap<>();
                params.put("uid",uid);
                activityChange(MY_PROFILE_MOBILE_ACTIVITY,params,REQUEST_CODE_MY_PROFILE_MOBILE_CHANGE);
            }
        });

        //修改电子邮箱
        rl_my_profile_email.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> params = new HashMap<>();
                params.put("uid",uid);
                activityChange(MY_PROFILE_EMAIL_ACTIVITY,params,REQUEST_CODE_MY_PROFILE_EMAIL_CHANGE);
            }
        });

        //修改密码
        rl_my_profile_password.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> params = new HashMap<>();
                params.put("uid",uid);
                activityChange(MY_PROFILE_PASSWORD_ACTIVITY,params,REQUEST_CODE_MY_PROFILE_PASSWORD_CHANGE);
            }
        });

        //修改性别
        rl_my_profile_gender.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> params = new HashMap<>();
                params.put("uid",uid);
                params.put("user_gender",tv_my_profile_gender_content.getText().toString());
                activityChange(MY_PROFILE_GENDER_ACTIVITY,params,REQUEST_CODE_MY_PROFILE_GENDER_CHANGE);
            }
        });
    }

    /**
     * 初始化组件内容
     */
    private void setViewContent(){

        //展示用户已选择头像
        String portraitPath = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, SpConstant.USER_PORTRAIT_PATH_KEY+uid);

        if(null == portraitPath || "".equals(portraitPath) || !new File(portraitPath).exists()){
            Log.e(TAG, "setViewContent: -------------- 用户头像不存在----------"+portraitPath);
            return;
        }
        iv_my_profile_user_portrait.setImageBitmap(BitmapFactory.decodeFile(portraitPath));
    }

    /**
     * 向服务器请求数据
     */
    private void getDataFromWeb() {

        //获得页面跳转后传递过来的uid
        if (null != bundle && null != bundle.getString("uid")) {
            uid = bundle.getString("uid");

            //查询用户所有信息
            new GetJsonFromWebJob(WebConstant.GET_USER_INFO_PATH + uid, WebConstant.GET, null, REQUEST_SIGN_GET_USER_INFO_BY_UID, MyProfileActivity.this).start();
        }
    }

    /***********************************************************************************************/
    /**                                 私有封装方法                                               **/
    /***********************************************************************************************/

    /**
     * 自定义app缓存文件夹下的文件路径
     * @param fileName 文件名称
     * @return 拼接完成的文件路径
     */
    private String getPortraitPath(String fileName){

        String storageState = Environment.getExternalStorageState();
        if(Environment.MEDIA_REMOVED.equals(storageState)){
            Log.e(TAG, "getPortraitPath: 外部存储设备SD卡没有，无法存储");
            return null;
        }

        File mediaCacheDir = this.getExternalCacheDir();
        if(!mediaCacheDir.exists()){
            Log.e(TAG, "getPortraitPath: 所取路径不存在" );
            return null;
        }

        return mediaCacheDir.getPath() + File.separator + fileName;
    }

    /**
     * 获得图片后 将其地址保存到sp中便于之后取值
     */
    private String savePortraitPathToSP(){

        //拼接图片存储路径
        String storagePath = getPortraitPath(MyProfileConstant.COMPRESS_USER_PORTRAIT_FILE_NAME);

        //将存储路径保存在sp中
        Map<String,String> params = new HashMap<>();
        params.put(SpConstant.USER_PORTRAIT_PATH_KEY+uid,storagePath);
        handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME,params);

        return storagePath;
    }


    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: -----------" + webResult);

        if (REQUEST_SIGN_GET_USER_INFO_BY_UID == webSign && webResult.contains("none user")) {
            Log.e(TAG, "dealDataFromWeb: 用户信息不存在");
            return;
        }

        //设置用户信息
        if (REQUEST_SIGN_GET_USER_INFO_BY_UID == webSign && !"".equals(webResult)) {
            UserInfoByUidResult userInfoByUidResult = gson.fromJson(webResult, UserInfoByUidResult.class);

            String userName = userInfoByUidResult.getUsername();
            String mobile = userInfoByUidResult.getMobile();
            String email = userInfoByUidResult.getEmail();
            String gender = userInfoByUidResult.getGender();

            tv_my_profile_name_content.setText(null == userName ? "Volta_"+uid : userName);
            tv_my_profile_mobile_content.setText(null == mobile ? "----" : mobile);
            tv_my_profile_email_content.setText(null == email ? "----" : email);
            tv_my_profile_gender_content.setText(null == gender ? "----" : ("0".equals(gender)?"Male":"Female"));
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Warning");
                builder.setMessage("You are signed in at another location...");

                builder.setPositiveButton("I know", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                e.printStackTrace();
            }
            return;
        }
    }

    /**
     * 处理 带结果的页面 跳转后 返回时携带的数据
     * @param requestCode 请求码
     * @param resultCode 结果码
     * @param data 数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //隐藏弹出框
        bottomPopWindow.dismissing();

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {

                //获取用户所选择图片的uri地址
                case REQUEST_CODE_GET_SYSTEM_PICTURE:

                    if (null == data || null == data.getData()) {
                        Log.e(TAG, "onActivityResult: ---------------- 未接收到所选择图片的uri地址");
                        return;
                    }

                    //压缩图片并存储
                    userPortrait = BitmapUtil.compressBitmapByUri(data.getData(),MyProfileConstant.TARGET_COMPRESS_HEIGHT,MyProfileConstant.TARGET_COMPRESS_WIDTH,savePortraitPathToSP(),MyProfileActivity.this);
                    //展示头像
                    iv_my_profile_user_portrait.setImageBitmap(userPortrait);
                    break;

                //自系统照相机应用返回
                case REQUEST_CODE_GET_SYSTEM_CAMERA:

                    File file = new File(imageFilePath);
                    if(null == file || !file.exists()){
                        Log.e(TAG, "onActivityResult: ----------------- 照片不存在");
                        return;
                    }

                    //压缩图片并存储
                    userPortrait = BitmapUtil.compressBitmapByPath(imageFilePath,MyProfileConstant.TARGET_COMPRESS_HEIGHT,MyProfileConstant.TARGET_COMPRESS_WIDTH,savePortraitPathToSP());
                    //展示头像
                    iv_my_profile_user_portrait.setImageBitmap(userPortrait);
                    break;

                //自修改手机号页面返回
                case REQUEST_CODE_MY_PROFILE_MOBILE_CHANGE:
                    String mobile_num = null == data.getExtras()? "----" :data.getExtras().getString("mobile_num");
                    tv_my_profile_mobile_content.setText(mobile_num);
                    break;

                //自修改邮箱地址页面返回
                case REQUEST_CODE_MY_PROFILE_EMAIL_CHANGE:
                    String email_address = null == data.getExtras()? "----" :data.getExtras().getString("email_address");
                    tv_my_profile_email_content.setText(email_address);
                    break;

                //自修改性别页面返回
                case REQUEST_CODE_MY_PROFILE_GENDER_CHANGE:
                    String gender = null == data.getExtras()?"----":data.getExtras().getString("checkGender");
                    tv_my_profile_gender_content.setText(gender);
                    break;

                //自修改姓名页面返回
                case REQUEST_CODE_MY_PROFILE_NAME_CHANGE:
                    String username = null == data.getExtras()?("Volta_"+uid):data.getExtras().getString("username");
                    tv_my_profile_name_content.setText(username);
                    break;

                //自修改密码页面返回
                case REQUEST_CODE_MY_PROFILE_PASSWORD_CHANGE:
                    Toast.makeText(this.getApplicationContext(), ToastConstant.MODIFY_PASSWORD_SUCCESS, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    /**
     * 监听回退按钮事件
     */
    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }
}
